/**
 * Mars3D加载工具
 * 处理Mars3D和Cesium的加载检查
 */

// 检查Mars3D是否加载完成
export const checkMars3DLoaded = () => {
  return new Promise((resolve, reject) => {
    // 如果已经加载，直接返回
    if (typeof window.mars3d !== 'undefined' && typeof window.Cesium !== 'undefined') {
      resolve(true)
      return
    }

    let attempts = 0
    const maxAttempts = 100 // 10秒超时
    
    const checkInterval = setInterval(() => {
      attempts++
      
      if (typeof window.mars3d !== 'undefined' && typeof window.Cesium !== 'undefined') {
        clearInterval(checkInterval)
        console.log('Mars3D和Cesium加载完成')
        resolve(true)
      } else if (attempts >= maxAttempts) {
        clearInterval(checkInterval)
        console.error('Mars3D加载超时')
        reject(new Error('Mars3D加载超时，请检查网络连接'))
      }
    }, 100)
  })
}

// 动态加载Mars3D脚本（备用方案）
export const loadMars3DScripts = () => {
  return new Promise((resolve, reject) => {
    // 如果已经加载，直接返回
    if (typeof window.mars3d !== 'undefined') {
      resolve()
      return
    }

    // Cesium脚本
    const cesiumScript = document.createElement('script')
    cesiumScript.src = 'https://unpkg.com/mars3d-cesium@1.112.0/Build/Cesium/Cesium.js'
    cesiumScript.onload = () => {
      // 设置Cesium基础路径
      window.CESIUM_BASE_URL = 'https://unpkg.com/mars3d-cesium@1.112.0/Build/Cesium/'
      
      // Mars3D脚本
      const mars3dScript = document.createElement('script')
      mars3dScript.src = 'https://unpkg.com/mars3d@3.6.0/dist/mars3d.min.js'
      mars3dScript.onload = () => {
        console.log('Mars3D脚本加载完成')
        resolve()
      }
      mars3dScript.onerror = () => {
        reject(new Error('Mars3D脚本加载失败'))
      }
      document.head.appendChild(mars3dScript)
    }
    cesiumScript.onerror = () => {
      reject(new Error('Cesium脚本加载失败'))
    }
    document.head.appendChild(cesiumScript)
  })
}

// 获取Mars3D版本信息
export const getMars3DVersion = () => {
  if (typeof window.mars3d !== 'undefined') {
    return window.mars3d.version || '未知版本'
  }
  return 'Mars3D未加载'
}

// 检查网络连接
export const checkNetworkConnection = () => {
  return new Promise((resolve) => {
    const img = new Image()
    img.onload = () => resolve(true)
    img.onerror = () => resolve(false)
    img.src = 'https://unpkg.com/mars3d@3.6.0/dist/mars3d.min.js?' + Date.now()
  })
}

// Mars3D初始化配置
export const getDefaultMapOptions = () => {
  return {
    scene: {
      center: { lat: 31.686, lng: 117.226, alt: 15000000, heading: 348, pitch: -50 },
      showSun: true,
      showMoon: true,
      showSkyBox: true,
      showSkyAtmosphere: true,
      fog: true,
      fxaa: true,
      globe: {
        depthTestAgainstTerrain: false,
        showGroundAtmosphere: true,
        enableLighting: false
      }
    },
    control: {
      baseLayerPicker: true,
      homeButton: true,
      sceneModePicker: true,
      navigationHelpButton: true,
      fullscreenButton: true,
      geocoder: false,
      timeline: false,
      animation: false,
      vrButton: false,
      infoBox: true,
      selectionIndicator: true
    },
    terrain: {
      url: '//data.mars3d.cn/terrain'
    },
    basemaps: [
      {
        name: '天地图影像',
        icon: '//data.mars3d.cn/img/thumbnail/tianditu_img.png',
        type: 'tdt',
        layer: 'img_d',
        show: true
      },
      {
        name: '天地图矢量',
        icon: '//data.mars3d.cn/img/thumbnail/tianditu_vec.png',
        type: 'tdt',
        layer: 'vec_d'
      },
      {
        name: 'OSM',
        icon: '//data.mars3d.cn/img/thumbnail/osm.png',
        type: 'xyz',
        url: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
        subdomains: ['a', 'b', 'c']
      }
    ]
  }
}